<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png" />
    <input type="file" @change="handleUpload($event)" />
    <HelloWorld msg="Welcome to Your Vue.js App" />
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from "@/components/HelloWorld.vue";

const dataURL2Blob = dataurl => {
  let arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
};

const readFile = inputFile => {
  const extention = inputFile.name
    .substring(inputFile.name.lastIndexOf(".") + 1)
    .toLowerCase();
  const fr = new FileReader();

  return new Promise((resolve, reject) => {
    fr.onerror = () => {
      fr.abort();
      reject("reject");
    };
    fr.onload = () => {
      if (["jpg", "bmp", "gif", "png", "jpeg"].includes(extention)) {
        resolve(fr.result);
      } else {
        resolve(dataURL2Blob(fr.result));
      }
    };
    fr.readAsDataURL(inputFile);
  });
};

export default {
  name: "Home",
  components: {
    HelloWorld
  },
  mounted() {
    this.$store.dispatch("login");
  },
  methods: {
    async handleUpload(event) {
      try {
        // use 1
        const fileContents = await readFile(event.target.files[0]);
        console.log(fileContents);

        // use 2
        readFile(event.target.files[0]).then(fc => {
          // TODO
          console.log(fc);
        });
      } catch (e) {
        console.log(e.message);
      }
    }
  }
};
</script>
